import React, { Component } from 'react';
import { CloudUploadOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Row, Col, Input, Select, Modal, Upload, Button, message,
} from 'antd';
import { FormComponentProps } from '@ant-design/compatible/es/form';

const { Option } = Select;

interface SaveAndUpdateProps extends FormComponentProps {
  detail: any;
  visible: boolean;
  logsList: any;
  gardenList: any;
  fetchAction: (typeName: string, payload: any) => void;
  showModal: (status: boolean) => void;
}

interface SaveAndUpdateState {
  formValues: any;
  fileList: any;
  fileUrl: string;
  saveType: number;
}

class SaveAndUpdateElem extends Component<SaveAndUpdateProps, SaveAndUpdateState> {
  state = {
    formValues: {},
    fileList: [],
    fileUrl: '',
    saveType: 1,
  }

  static getDerivedStateFromProps(nextProps: SaveAndUpdateProps, perState: SaveAndUpdateState) {
    const { detail, visible } = nextProps;
    const { fileUrl } = perState;
    if (detail.fileUrl && fileUrl !== detail.fileUrl && visible) {
      return ({
        fileList: [{
          name: detail.fileUrl.length > 8 ? `${detail.fileUrl.substring(0, 8)}...` : detail.fileUrl,
          url: detail.fileUrl,
          uid: detail.fileUrl,
        }],
        fileUrl: detail.fileUrl,
      });
    }
    if (detail && detail.type) {
      return ({
        saveType: detail.type,
      });
    }
    return null;
  }

  handleSubmit = () => {
    const { formValues, fileList }: any = this.state;
    const { form: { validateFields }, fetchAction, detail } = this.props;
    validateFields((errors, values) => {
      if (!errors) {
        if (values.type === 1 && !formValues.file && fileList.length <= 0) {
          message.error('请上传语音文件');
        } else {
          const params = {
            ...values,
            ...formValues,
          };
          if (detail.id) params.id = detail.id;
          delete params.file_wav;
          fetchAction('saveAndUpdate', params);
          this.handleCancel();
        }
      }
    });
  }

  handleCancel = () => {
    const { showModal } = this.props;
    showModal(false);
    this.setState({
      formValues: {},
      fileList: [],
      fileUrl: '',
      saveType: 1,
    });
  }

  handleChangeType = (value: number) => {
    this.setState({
      saveType: value,
    });
  }

  handlePreview = async (file: any) => {
    window.open(file.url);
  }

  handleUpload = ({ file, fileList }: any) => {
    const { formValues } = this.state;
    if (fileList.length > 0) fileList[fileList.length - 1].name = '语音文件';
    this.setState({
      fileList: fileList.length <= 0 ? [] : [fileList[fileList.length - 1]],
      formValues: {
        ...formValues,
        file: fileList.length <= 0 ? '' : fileList[fileList.length - 1].originFileObj,
      },
    });
  }

  render() {
    const { fileList, saveType } = this.state;
    const {
      form: { getFieldDecorator },
      detail,
      visible,
      logsList,
      gardenList,
    } = this.props;

    return (
      <Modal
        title="编辑分区"
        width={600}
        visible={visible}
        destroyOnClose
        onOk={this.handleSubmit}
        onCancel={this.handleCancel}
      >
        <Form hideRequiredMark className="tableListForm">
          <Row gutter={12}>
            <Col md={12} sm={24}>
              <Form.Item label="　　分区" colon={false}>
                {getFieldDecorator('name', ({
                  initialValue: detail.name,
                  rules: [{ required: true, message: '请输入分区' }],
                }))(
                  <Input allowClear placeholder="请输入" />,
                )}
              </Form.Item>
            </Col>
            <Col md={12} sm={24}>
              <Form.Item label="场景类型" colon={false}>
                {getFieldDecorator('type', ({
                  initialValue: detail.type || 1,
                  rules: [{ required: true, message: '请选择场景类型' }],
                }))(
                  <Select
                    placeholder="请选择"
                    onChange={this.handleChangeType}
                    disabled={detail.type && true}
                  >
                    <Option value={1}>校园</Option>
                    <Option value={2}>小区</Option>
                  </Select>,
                )}
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={12}>
            <Col md={12} sm={24}>
              {saveType === 1 && (
                <Form.Item label="物流中心" colon={false}>
                  {getFieldDecorator('logisId', ({
                    initialValue: detail.logisId,
                    rules: [{ required: true, message: '请选择物流中心' }],
                  }))(
                    <Select
                      showSearch
                      placeholder="请选择"
                      disabled={detail.logisName && true}
                      filterOption={(input: any, option: any) => (
                        option.props.children.toLowerCase().indexOf(
                          input.toLowerCase(),
                        ) >= 0
                      )}
                    >
                      {detail.logisId && <Option value={detail.logisId}>{detail.logisName}</Option>}
                      {logsList.map((item: any) => (
                        <Option value={item.id} key={item.id}>{item.name}</Option>
                      ))}
                    </Select>,
                  )}
                </Form.Item>
              )}
              {saveType === 2 && (
                <Form.Item label="　　小区" colon={false}>
                  {getFieldDecorator('gardenId', ({
                    initialValue: detail.gardenId,
                    rules: [{ required: true, message: '请选择小区' }],
                  }))(
                    <Select
                      showSearch
                      placeholder="请选择"
                      disabled={detail.logisName && true}
                      filterOption={(input: any, option: any) => (
                        option.props.children.toLowerCase().indexOf(
                          input.toLowerCase(),
                        ) >= 0
                      )}
                    >
                      {detail.logisId && <Option value={detail.logisId}>{detail.logisName}</Option>}
                      {gardenList.map((item: any) => (
                        <Option value={item.id} key={item.id}>{item.name}</Option>
                      ))}
                    </Select>,
                  )}
                </Form.Item>
              )}
            </Col>
            {saveType === 1 && (
              <Col md={12} sm={24}>
                <Form.Item label="语音文件" colon={false}>
                  {getFieldDecorator('file_wav', {
                    rules: [{ required: false, message: '请选择文件' }],
                  })(
                    <Upload
                      accept=".mp3,.wav"
                      style={{ fontSize: 12 }}
                      fileList={fileList}
                      beforeUpload={() => false}
                      onPreview={this.handlePreview}
                      onChange={this.handleUpload}
                    >
                      <Button type="primary" size="small" ghost>
                        <CloudUploadOutlined />上传
                      </Button>
                    </Upload>,
                  )}
                </Form.Item>
              </Col>
            )}
          </Row>
        </Form>
      </Modal>
    );
  }
}

export default Form.create<SaveAndUpdateProps>()(SaveAndUpdateElem);
